package saucaca.fragment;

import java.util.ArrayList;
import java.util.List;

import saucaca.CustomView.CircularImageView;
import saucaca.CustomView.MaterialSection;
import saucaca.CustomView.MaterialSectionListener;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Object.MenuObject;
import saucaca.Util.AppController;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.lemon.kenhnhacvn.BaseActivity;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;
import com.nineoldandroids.view.ViewHelper;

@SuppressLint("NewApi")
@SuppressWarnings("rawtypes")
public class MenuFragment extends Fragment implements MaterialSectionListener {
	private LinearLayout menu_Header;
	private LinearLayout menu_Content;
	private LinearLayout menu_Bottom;

	private List<MaterialSection> headerMenuList;
	private List<MaterialSection> contentMenuList;
	private List<MaterialSection> bottomMenuList;
	private MaterialSection currentSection;

	private Resources resources;
	private float density;

	public static final int BOTTOM_SECTION_START = 100;

	ArrayList<MenuObject> listMenu;
	public static final String key_code = "code";
	public static final String key_fragment = "fragment";

	CircularImageView accountAvatar;
	ImageLoader imageLoader;
	TextView txtNameuser;
	Resources res;
	boolean isOnline = true;
	boolean isLogin = false;
	MainActivity mainActivity;
	public Button btnLogin;
	LinearLayout footerChude, footerTheloai, footerCaidat, footerThongtin, footerUngdung, headerTrangchu, headerNct, headerAccount;
	ArrayList<LinearLayout> listMenuLinear;
	ProgressDialog progressDialog;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof MainActivity) {
			mainActivity = (MainActivity) activity;
		}
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.menu2, container, false);
		findViewById(view);
		try {
			imageLoader = ((BaseActivity) getActivity()).imageLoader;
		} catch (Exception e) {
			imageLoader = AppController.getInstance().getImageLoader();
		}
		progressDialog = new ProgressDialog(getActivity());
		headerMenuList = new ArrayList<MaterialSection>();
		contentMenuList = new ArrayList<MaterialSection>();
		bottomMenuList = new ArrayList<MaterialSection>();
		resources = this.getResources();
		density = resources.getDisplayMetrics().density;

		addSection(newSection("Online", new MaterialSectionListener() {
			@Override
			public void onClick(MaterialSection section) {
				if (!progressDialog.isShowing())
					progressDialog.isShowing();
				if(BaseEngine.isConnectionAvailable(mainActivity)){
					new getService().execute("");
					}else {
						Toast.makeText(mainActivity, mainActivity.getResources().getString(R.string.error_connected), Toast.LENGTH_SHORT).show();
					}
			}
		}));

		addHeaderSection(newSection(resources.getString(R.string.menu_nhaccuatoi), R.drawable.bar_nhacct_icon, new LocalAllMusic()));
		addSubheader("Kênh nhạc", menu_Header);
		addSubheader("Công cụ", menu_Bottom);
		addBottomSection(newSection(resources.getString(R.string.menu_caidat), R.drawable.bar_setup_icon, new SettingFragment()));
		addBottomSection(newSection(resources.getString(R.string.menu_thongtin), R.drawable.bar_info_icon, new InforFragment()));
		addBottomSection(newSection(resources.getString(R.string.menu_ungdung), R.drawable.bar_app_store, new MaterialSectionListener() {

			@Override
			public void onClick(MaterialSection section) {
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Lemon+Media")));

			}
		}));
		if (contentMenuList.size() > 0) {
			currentSection = contentMenuList.get(0);
		}
		headerMenuList.get(0).select();
		if(BaseEngine.isConnectionAvailable(mainActivity)){
			new getService().execute("");
			}else {
				Toast.makeText(mainActivity, mainActivity.getResources().getString(R.string.error_connected), Toast.LENGTH_SHORT).show();
			}
		return view;
	}

	void findViewById(View view) {
		menu_Header = (LinearLayout) view.findViewById(R.id.menu_header);
		menu_Content = (LinearLayout) view.findViewById(R.id.menu_content);
		menu_Bottom = (LinearLayout) view.findViewById(R.id.menu_bottom);
		btnLogin = (Button) view.findViewById(R.id.list_menu_logo_buttonlogin);
		headerAccount = (LinearLayout) view.findViewById(R.id.layout_username);
		accountAvatar = (CircularImageView) view.findViewById(R.id.account_avatar);
		txtNameuser = (TextView) view.findViewById(R.id.header_account_name);
		String user = null;
		try {
			user = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (user != null) {
			if (!user.equals("")) {
				btnLogin.setText(mainActivity.getResources().getString(R.string.logout));
				isLogin = true;
				changedLoginstatus(true);
			}
		} else
			btnLogin.setText(mainActivity.getResources().getString(R.string.login));
		btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isLogin) {
					logoutDialog();
				} else {
					String newContent = AccountLoginFragment.class.getName();
					switchFragment(newContent);
					// Intent intent = new Intent((MainActivity)mainActivity,
					// LoginActivity.class);
					// mainActivity.startActivity(intent);
				}
			}
		});

		headerAccount.setOnClickListener(clickListener);
	}

	View.OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			SelectMenu(-1);
			String newContent = null;
			switch (v.getId()) {
			case R.id.layout_username:
				String type = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_typelogin);
				if (type != null && type.equals(TagName.KeyPreference_Account))
					newContent = AccountUpdateInfoFragment.class.getName();
				break;
			}
			if (newContent != null) {
				switchMenuFragment(newContent);
			}
		}
	};

	public void logoutDialog() {
		AlertDialog builder = new AlertDialog.Builder(mainActivity).create();
		builder.setMessage(mainActivity.getResources().getString(R.string.logout_warning));
		builder.setCancelable(false);
		builder.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				changedLoginstatus(false);
			}
		});
		builder.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.show();
	}

	@SuppressWarnings("unused")
	public void changedLoginstatus(boolean isLoggin) {
		if (isLoggin) {
			btnLogin.setText(getResources().getString(R.string.logout));
			isLogin = isLoggin;
			String strAvatar = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_avatar);
			String strAvatar_url = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_avatar_url);
			String strName = PreferenceUtils.getString(mainActivity, TagName.KeyPreference_fullname);
			int mExpandOnDragHeight = (int) getResources().getDimension(R.dimen.header_account);
			ViewGroup.LayoutParams params = headerAccount.getLayoutParams();
			params.height = mExpandOnDragHeight;
			accountAvatar.setImageResource(R.drawable.cn_avatar_cover);
			if (strAvatar != null) {
				try {
					Bitmap bitmap = BaseEngine.BitmapFromBase64(strAvatar);
					accountAvatar.setImageBitmap(bitmap);
				} catch (Exception e) {
					e.printStackTrace();
					if (strAvatar_url != null)
						// ImageLoader.getInstance().loadImage(strAvatar_url,
						// new SimpleImageLoadingListener() {
						// @Override
						// public void onLoadingComplete(String imageUri, View
						// view, Bitmap loadedImage) {
						// super.onLoadingComplete(imageUri, view, loadedImage);
						// PreferenceUtils.putString(mainActivity,
						// TagName.KeyPreference_avatar,
						// BaseEngine.BitmapTobase64(loadedImage));
						// accountAvatar.setImageBitmap(loadedImage);
						// }
						// });
						imageLoader.get(strAvatar_url, new ImageLoader.ImageListener() {
							@Override
							public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
								PreferenceUtils.putString(mainActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(response.getBitmap()));
								accountAvatar.setImageBitmap(response.getBitmap());
							}

							@Override
							public void onErrorResponse(VolleyError arg0) {
							}
						});
				}
			} else if (strAvatar_url != null) {
				// ImageLoader.getInstance().loadImage(strAvatar_url, new
				// SimpleImageLoadingListener() {
				// @Override
				// public void onLoadingComplete(String imageUri, View view,
				// Bitmap loadedImage) {
				// super.onLoadingComplete(imageUri, view, loadedImage);
				// PreferenceUtils.putString(mainActivity,
				// TagName.KeyPreference_avatar,
				// BaseEngine.BitmapTobase64(loadedImage));
				// accountAvatar.setImageBitmap(loadedImage);
				// }
				// });
				imageLoader.get(strAvatar_url, new ImageLoader.ImageListener() {
					@Override
					public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
						PreferenceUtils.putString(mainActivity, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(response.getBitmap()));
						accountAvatar.setImageBitmap(response.getBitmap());
					}

					@Override
					public void onErrorResponse(VolleyError arg0) {
					}
				});
			} else {
			}
			txtNameuser.setText(strName);
		} else {
			if (mainActivity.mCurrentFragment.getClass().getName().equals(AccountUpdateInfoFragment.class.getName())) {
				if (BaseEngine.isConnectionAvailable(mainActivity))
					mainActivity.menuselect(home.class.getName());
				else
					mainActivity.menuselect(LocalAllMusic.class.getName());
			} else if (mainActivity.mCurrentFragment.getClass().getName().equals(LocalAllMusic.class.getName())) {
				((LocalAllMusic) mainActivity.mCurrentFragment).logout();
			}
			ViewGroup.LayoutParams params = headerAccount.getLayoutParams();
			params.height = 0;
			btnLogin.setText(mainActivity.getResources().getString(R.string.login));
			PreferenceUtils.clear(mainActivity);
			isLogin = false;
		}
	}

	@Override
	public void onClick(MaterialSection section) {
		switch (section.getTarget()) {
		case MaterialSection.TARGET_FRAGMENT:
			switchMenuFragment(section.getTargetFragment().getClass().getName());
			break;
		case MaterialSection.TARGET_ACTIVITY:
			// this.startActivity(section.getTargetIntent());
			// layout.closeDrawer(drawer);
			break;
		// TARGET_LISTENER viene gestito internamente
		case MaterialSection.TARGET_LISTENER:
			// if (!deviceSupportMultiPane())
			// layout.closeDrawer(drawer);
		default:
			break;
		}
		currentSection = section;

		int position = section.getPosition();

		SelectMenu(position);
	}

	void SelectMenu(int position) {
		for (MaterialSection mySection : headerMenuList) {
			if (position != mySection.getPosition())
				mySection.unSelect();
		}
		for (MaterialSection mySection : contentMenuList) {
			if (position != mySection.getPosition())
				mySection.unSelect();
		}
		for (MaterialSection mySection : bottomMenuList) {
			if (position != mySection.getPosition())
				mySection.unSelect();
		}
	}

	private void switchMenuFragment(String fragment) {
		if (getActivity() == null)
			return;
		else if (getActivity() instanceof MainActivity) {
			MainActivity a = (MainActivity) getActivity();
			// a.mSilidingUP.collapsePanel();
			// a.switchContent(fragment);
			a.menuselect(fragment);

		}
	}

	private void switchFragment(String fragment) {
		if (getActivity() == null)
			return;
		else if (getActivity() instanceof MainActivity) {
			MainActivity a = (MainActivity) getActivity();
			// a.mSilidingUP.collapsePanel();
			a.switchContent(fragment);

		}
	}

	public void addHeaderSection(MaterialSection section) {
		section.setPosition(contentMenuList.size());
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
		headerMenuList.add(section);
		menu_Header.addView(section.getView(), params);
	}

	public void addSection(MaterialSection section) {
		section.setPosition(contentMenuList.size());
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
		contentMenuList.add(section);
		menu_Content.addView(section.getView(), params);
	}

	public void addBottomSection(MaterialSection section) {
		section.setPosition(BOTTOM_SECTION_START + bottomMenuList.size());
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (48 * density));
		bottomMenuList.add(section);
		menu_Bottom.addView(section.getView(), params);
	}

	public void addDivisor(ViewGroup viewGroup) {
		View view = new View(getActivity());
		view.setBackgroundColor(Color.parseColor("#8C8F8D"));
		// height 1 px
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
		params.setMargins(10, (int) (8 * density), 10, (int) (8 * density));

		viewGroup.addView(view, params);
	}

	public void addSubheader(CharSequence title, ViewGroup viewGroup) {
		View subheader = LayoutInflater.from(getActivity()).inflate(R.layout.layout_material_subheader, viewGroup, false);
		TextView subheaderTitle = (TextView) subheader.findViewById(R.id.subheader_text);
		subheaderTitle.setText(title);

		// add custom separator on top of subheader
		View view = new View(getActivity());
		view.setBackgroundColor(Color.parseColor("#ffffff"));
		// view.setAlpha(0.54f);
		ViewHelper.setAlpha(view, 0.54f);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
		params.setMargins(10, (int) (8 * density), 10, 0);

		viewGroup.addView(subheader);
		viewGroup.addView(view, params);
	}

	public MaterialSection newSection(String title, Drawable icon, Fragment target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_FRAGMENT);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, String icon, Fragment target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_FRAGMENT);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, Drawable icon, Intent target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_ACTIVITY);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, Drawable icon, MaterialSectionListener target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_LISTENER);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, Bitmap icon, Fragment target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_FRAGMENT);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, Bitmap icon, Intent target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_ACTIVITY);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, Bitmap icon, MaterialSectionListener target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), true, MaterialSection.TARGET_LISTENER);
		section.setOnClickListener(this);
		section.setIcon(icon);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, int icon, Fragment target) {
		return newSection(title, resources.getDrawable(icon), target);
	}

	public MaterialSection newSection(String title, int icon, Intent target) {
		return newSection(title, resources.getDrawable(icon), target);
	}

	public MaterialSection newSection(String title, int icon, MaterialSectionListener target) {
		return newSection(title, resources.getDrawable(icon), target);
	}

	public MaterialSection newSection(String title, Fragment target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), false, MaterialSection.TARGET_FRAGMENT);
		section.setOnClickListener(this);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, Intent target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), false, MaterialSection.TARGET_ACTIVITY);
		section.setOnClickListener(this);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection newSection(String title, MaterialSectionListener target) {
		MaterialSection section = new MaterialSection<Fragment>(getActivity(), false, MaterialSection.TARGET_LISTENER);
		section.setOnClickListener(this);
		section.setTitle(title);
		section.setTarget(target);

		return section;
	}

	public MaterialSection getCurrentSection() {
		return currentSection;
	}

	private class getService extends AsyncTask<String, Void, String> {
		final String TAG = "JsonReader";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... urls) {
			String str = null;
			str = WServiceLib.getHomeString();
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				try {
					JsonReader.readHomeData(result);
					SetmenuOnline();
				} catch (Exception e) {
					Log.e(TAG, "_____Exception_______:" + e.toString());
					e.printStackTrace();
				}
			}
		}
	}

	public void SetmenuOnline() {
		if (progressDialog.isShowing())
			progressDialog.hide();
		ArrayList<MenuObject> list = (ArrayList<MenuObject>) HomeData.homeListMENU;
		if (list != null) {
			isOnline = true;
			listMenu = list;
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					contentMenuList.clear();
					menu_Content.removeAllViews();
					addSection(newSection(resources.getString(R.string.menu_home), R.drawable.bar_home_icon, new home()));
					for (int i = 0; i < listMenu.size(); i++) {
						addSection(newSection(listMenu.get(i).getName(), listMenu.get(i).getAvatar(), chooseFragment(listMenu.get(i))));
					}
					// addSection(newSection(resources.getString(R.string.menu_theloai),R.drawable.bar_nhactre_icon,
					// new CateFragment()));
					addSection(newSection(resources.getString(R.string.menu_chude), R.drawable.bar_dance_icon, new TopicFragment2()));
					switchMenuFragment(home.class.getName());
					contentMenuList.get(0).select();
					headerMenuList.get(0).unSelect();
				}
			});
		}
	}

	public Fragment chooseFragment(MenuObject menuObject) {
		if (menuObject.getMenuCode().equals("0001")) {
			return new home();
		} else if (menuObject.getMenuCode().equals("0002")) {
			return new OnlineSongFragment();
		} else if (menuObject.getMenuCode().equals("0003")) {
			return new ArtistListfragment();
		} else if (menuObject.getMenuCode().equals("0004")) {
			return new VideoFragment();
		} else if (menuObject.getMenuCode().equals("0005")) {
			return new AlbumFragment();
		} else if (menuObject.getMenuCode().equals("0006")) {
			return new NewFragment();
		} else if (menuObject.getMenuCode().equals("0007")) {
			return new BXHfragment();
		} else if (menuObject.getMenuCode().equals("0008")) {
			return new TvShowFragment2();
		} else if (menuObject.getMenuCode().equals("0009")) {
			return new RingtoneFragment();
		} else {
			return new FragmentErrorConnect();
		}
	}

}
